package com.mm.cloud.common.mq.converter;

import com.mm.cloud.common.mq.message.CustomMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 序列化过滤转换
 *
 * @author mr
 * @since 2021-09-15
 */
@Slf4j
@Component
public class MessageConverterFilter {

    @Autowired
    private MessageConverter messageConverter;

    /**
     * 消息体数据转换
     *
     * @param tClass  数据类型
     * @param message 消息主体
     * @return T 泛型对象
     */
    public <T> T to(Class<T> tClass, Message message) {
        Object obj = fromMessage(message);
        if (tClass.isInstance(obj)) {
            return tClass.cast(obj);
        }
        log.error("message to type class error");
        return null;
    }

    /**
     * 消息数据
     * @param message
     * @return
     */
    public Object fromMessage(Message message) {
        CustomMessage me = toMessage(message);
        if (null != me) {
            return me.getMessage();
        }
        return null;
    }

    /**
     * 附加消息
     * @param message
     * @return
     */
    public CustomMessage toMessage(Message message) {
        try {
            return (CustomMessage) messageConverter.fromMessage(message);
        } catch (Exception e) {
            log.error("messageProperties:{}", message.getMessageProperties());
            log.error("MQ 反序列化异常", e);
        }
        return null;
    }

}
